#include "wx/wxprec.h"
#include "wx/colour.h"

#ifndef WX_PRECOMP
#include "wx/log.h"
#include "wx/utils.h"
#include "wx/gdicmn.h"
#endif

#if wxUSE_VARIANT
IMPLEMENT_VARIANT_OBJECT_EXPORTED( wxColour )
#endif

bool wxColourBase::FromString( const wxChar *str ) {
  if( str == NULL || str[0] == wxT( '\0' ) ) {
    return false;
  }
  if( wxStrncmp( str, wxT( "RGB" ), 3 ) == 0 ||
      wxStrncmp( str, wxT( "rgb" ), 3 ) == 0 ) {
    int red, green, blue;
    if( wxSscanf( &str[3], wxT( "(%d, %d, %d)" ), &red, &green, &blue ) != 3 ) {
      return false;
    }
    Set( ( unsigned char )wxClip( red, 0, 255 ),
         ( unsigned char )wxClip( green, 0, 255 ),
         ( unsigned char )wxClip( blue, 0, 255 ) );
  } else if( str[0] == wxT( '#' ) && wxStrlen( str ) == 7 ) {
    unsigned long tmp;
    if( wxSscanf( &str[1], wxT( "%lx" ), &tmp ) != 1 ) {
      return false;
    }
    Set( ( unsigned char )( tmp >> 16 ),
         ( unsigned char )( tmp >> 8 ),
         ( unsigned char )tmp );
  } else if( wxTheColourDatabase ) {
    wxColour clr = wxTheColourDatabase->Find( str );
    if( clr.Ok() )
      Set( ( unsigned char )clr.Red(),
           ( unsigned char )clr.Green(),
           ( unsigned char )clr.Blue() );
  }
  if( Ok() ) {
    return true;
  }
  wxLogDebug( wxT( "wxColour::Set - couldn't set to colour string '%s'" ), str );
  return false;
}

wxString wxColourBase::GetAsString( long flags ) const {
  wxString colName;
  if( flags & wxC2S_NAME ) {
    colName = wxTheColourDatabase->FindName( ( const wxColour & )( *this ) ).MakeLower();
  }
  if( colName.empty() && ( flags & wxC2S_CSS_SYNTAX ) ) {
    colName.Printf( wxT( "rgb(%d, %d, %d)" ),
                    Red(), Green(), Blue() );
  } else if( colName.empty() && ( flags & wxC2S_HTML_SYNTAX ) ) {
    colName.Printf( wxT( "#%02X%02X%02X" ),
                    Red(), Green(), Blue() );
  }
  wxASSERT_MSG( !colName.empty(), wxT( "Invalid wxColour -> wxString conversion flags" ) );
  return colName;
}

wxColour wxColourBase::CreateByName( const wxString& name ) {
  return wxColour( name );
}

void wxColourBase::InitFromName( const wxString& col ) {
  Set( col );
}
